<template>
  <block>
    <!-- 公共弹窗 调用方法开启 -->
    <message-modal
      ref="messageModalRef"
      :location="location"
      :tsActId="tsActId"
      @recheckUser="onRecheckUser"
      @finish="onMessageModalFinish"
      @registerSuccess="onRegisterSuccess"
    />
    <!-- eb会员绑定弹框 -->
    <eb-member-modal
      :location="location"
      ref="ebMemberModalRef"
      @recheckUser="onRecheckUser"
      @registerSuccess="onRegisterSuccess"
    />
    <!-- 特邀会员绑定弹框 -->
    <invited-member-modal
      ref="invitedMemberModalRef"
      :location="location"
      :tsActId="tsActId"
      @registerSuccess="onRegisterSuccess"
      @confirm="onInvitedMemberModalConfirm"
      @close="onInvitedMemberModalClose"
      @cancel="onInvitedMemberModalCancel"
    />
    <!-- eb邀请入会弹窗 -->
    <join-member-modal
      :location="location"
      ref="joinMemberModalRef"
      @confirm="onJoinMemberModalConfirm"
      @registerSuccess="onRegisterSuccess"
    />
    <!-- 年龄确认弹框 非会员 -->
    <age-confirm-modal
      ref="ageConfirmModalRef"
      :location="location"
      :tsActId="tsActId"
      @confirm="onAgeConfirmModalConfirm"
    />
    <!-- 年龄确认弹框 会员 -->
    <age-check-modal
      ref="ageCheckModalRef"
      :tsActId="tsActId"
      :location="location"
      @confirm="onAgeCheckModalConfirm"
    />
    <!-- sdk弹框 -->
    <sdk-modal ref="sdkModalRef" @confirm="onSdkModalConfirm" />
    <sdk-age-confirm-modal
      ref="sdkAgeConfirmModal"
      @confirm="onSdkAgeModalConfirm"
    />

    <!-- 专属注册：加入会员享专属权益 -->
    <!-- <new-register-join-member-modal
      ref="newRegisterJoinMemberModal"
      @recheckUser="onRecheckUser"
      @registerBtn="onRegisterBtn"
      @registerSuccess="onRegisterSuccess"
      @confirm="onJoinMemberModalConfirm"
    /> -->
  </block>
</template>

<script>
import ebMemberModal from "./eb-member-modal.vue";
import invitedMemberModal from "./invited-member-modal.vue";
import messageModal from "./message-modal.vue";
import sdkModal from "./sdk-modal.vue";
import ageCheckModal from "./age-check-modal.vue";
import ageConfirmModal from "./age-confirm-modal.vue";
import joinMemberModal from "./join-member-modal.vue";
import sdkAgeConfirmModal from "./sdk-age-confirm-modal.vue";
// import newRegisterJoinMemberModal from "./new-register-join-member-modal.vue";

import { getMessageModalTemplate } from "./static";
import { CUSTOMER_INFO } from "@/utils/constant";
import { mapState } from "vuex";
import {
  getTsProcessStatus,
  updatePolicyStatus,
  getTsInfoNoLogin,
  checkPolicy,
} from "./utils";
import tip from "@/utils/tip";

export default {
  name: "registerWidget",
  components: {
    sdkModal,
    ageCheckModal,
    ageConfirmModal,
    joinMemberModal,
    messageModal,
    invitedMemberModal,
    ebMemberModal,
    sdkAgeConfirmModal,
    // newRegisterJoinMemberModal,
  },
  props: {
    // 使用页面
    location: {
      type: String,
      default: "home",
    },
    // 外部传入false, 不执行skd弹窗和18周岁弹框的逻辑, 主要在其他组件中关闭
    entrance: {
      type: Boolean,
      default: true,
    },
    // 有的话, 就判定为ts活动
    tsActId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isUser: false,
      phoneNumber: "",
      tsEventDisabled: false,
      needUpdatePocliy: false, // 是否需要更新爱丁堡个人信息保护政策
      needUpdatePrivate: false, // 是否需要更新隐私协议
    };
  },
  computed: {
    ...mapState({
      skdModalChecked: (state) => state.skdModalChecked,
      ageModalChecked: (state) => state.ageModalChecked,
      foreignMobileDialog: (state) => state.foreignMobileDialog,
    }),
  },
  mounted() {
    if (this.entrance) {
      this.init();
    }
  },
  methods: {
    // 不用登录直接查询ts活动状态
    async checkTsEventState() {
      const res = await getTsInfoNoLogin(this.tsActId);
      const r = res.success || false;
      this.tsEventDisabled = !r;
      return r;
    },
    // ts活动不合法
    tsEventErrorMsg() {
      const duration = 2000;
      tip.plainText("活动状态异常", duration);
      setTimeout(() => {
        this.isForeignMobile("register-widget");
      }, duration + 500);
    },
    async init() {
      try {
        await this.$onLaunched;
        await this.getPrivacySetting();
        const res = await this.$commonFunction.commonLoginNew();
        if (res.code === 1000) {
          this.isUser = true;
          this.phoneNumber = res.data.mobile;
          await this.checkPolicyStatus(res);
        } else {
          throw res;
        }
      } catch (error) {
        this.isUser = false;
      }
      if (this.tsActId) {
        await this.checkTsEventState();
      }
      /** 判断sdk弹框 */
      if (!this.skdModalChecked || !this.ageModalChecked) {
        // this.$refs.sdkAgeConfirmModal.open();
        this.$refs.sdkAgeConfirmModal.open();
      } else {
        await this.onSdkAgeModalConfirm();
      }
    },
    async checkPolicyStatus(res) {
      let isAgreePolicy = await checkPolicy(res.data.jwt);
      if (isAgreePolicy !== "Yes") {
        this.needUpdatePocliy = true;
        this.$store.commit("changeAgeModalCheckedState", false);
      }
    },
    // 打开EB注册弹窗
    openJoinMemberModal() {
      this.$commonSensors.popupEvent("PopupExposure", {
        popup_type: "会员注册/绑定",
        popup_name: "入会弹窗",
      });
      this.$refs.joinMemberModalRef.open();
    },
    // 打开TS注册弹窗
    async openInvitedMemberModal() {
      this.$commonSensors.popupEvent("PopupExposure", {
        popup_type: "TS活动",
        popup_name: "TS入会弹窗",
      });
      this.$refs.invitedMemberModalRef.open(this.needUpdatePrivate);
    },
    // 是否是TS活动弹框
    getIsTsActive() {
      return this.tsActId ? true : false;
    },
    // 打开公共弹框(基于模板)
    openMessageModal(key) {
      if (!key) {
        return;
      }
      const isTsActive = this.getIsTsActive();
      if (!isTsActive && key === "NONE") {
        this.$refs.ebMemberModalRef.open();
        return;
      }
      const type = isTsActive ? "TARGET_SALES" : "NORMAL";
      const template = getMessageModalTemplate(type, key);
      if (template) {
        this.$refs.messageModalRef.open(template);
        if (key == "EVENT_NOT_INVITED_MEMBER") {
          getApp().commonssPopupTrack("PopupExposure", {}, type, key, {});
        }
      }
    },
    async onSdkAgeModalConfirm() {
      this.$store.commit("changeSkdModalCheckedState", true);
      this.$store.commit("changeAgeModalCheckedState", true);

      if (this.tsActId) {
        if (this.tsEventDisabled) {
          this.tsEventErrorMsg();
        } else if (this.isUser) {
          this.checkTsEvent();
        } else {
          this.isForeignMobile("age-confirm-modal");
        }
      } else {
        this.isForeignMobile("age-confirm-modal");
      }
    },
    async onSdkModalConfirm() {
      this.$store.commit("changeSkdModalCheckedState", true);
      if (this.isUser) {
        // 是会员,没有勾选18周岁或需要更新隐私协议
        if (!this.ageModalChecked || this.needUpdatePrivate) {
          if (this.needUpdatePocliy || this.needUpdatePrivate) {
            this.$refs.ageConfirmModalRef.open(
              this.needUpdatePocliy,
              this.needUpdatePrivate
            );
          } else {
            this.$refs.ageCheckModalRef.open();
          }
        } else {
          this.onAgeCheckModalConfirm();
        }
      } else {
        // 非会员
        const checkAgeConfirmModal = () => {
          if (!this.ageModalChecked) {
            this.$refs.ageConfirmModalRef.open(true, this.needUpdatePrivate);
          } else {
            this.onAgeConfirmModalConfirm();
          }
        };

        if (this.tsActId) {
          if (this.tsEventDisabled) {
            checkAgeConfirmModal();
          } else {
            this.openInvitedMemberModal();
          }
        } else {
          checkAgeConfirmModal();
        }
      }
    },
    // 21周算弹框(会员) 确认
    async onAgeCheckModalConfirm() {
      this.$store.commit("changeAgeModalCheckedState", true);
      getApp().sdkSetting();
      if (this.tsActId) {
        if (this.tsEventDisabled) {
          this.tsEventErrorMsg();
        } else {
          // TS活动下, 需要确认TS活动状态, 弹出对应提示
          await this.checkTsEvent();
        }
      } else {
        this.isForeignMobile("age-check-modal");
      }
    },
    getPrivacySetting() {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      if (!!wx.getPrivacySetting) {
        wx.getPrivacySetting({
          success: (res) => {
            if (res.needAuthorization) {
              // 需要弹出隐私协议
              this.needUpdatePrivate = true;
            }
          },
          complete: (res) => {
            let trackObj = Object.assign({}, customerInfo, res);
            wx.reportEvent("privacy_status", {
              privacy_params: JSON.stringify(trackObj),
            });
          },
        });
      } else {
        this.needUpdatePrivate = false;
      }
    },
    async checkTsEvent() {
      const res = await getTsProcessStatus(this.tsActId);
      this.openMessageModal(res.messageModalCode);
    },
    // 21周算弹框(非会员) 确认
    onAgeConfirmModalConfirm() {
      this.$store.commit("changeAgeModalCheckedState", true);
      if (this.tsActId) {
        if (this.tsEventDisabled) {
          this.tsEventErrorMsg();
        } else if (this.isUser) {
          this.checkTsEvent();
        } else {
          this.isForeignMobile("age-confirm-modal");
        }
      } else {
        this.isForeignMobile("age-confirm-modal");
      }
    },

    // 普通注册弹框确认
    onJoinMemberModalConfirm(ev) {
      const { messageModalCode } = ev;
      const isTsActive = this.getIsTsActive();
      const type = isTsActive ? "TARGET_SALES" : "NORMAL";
      getApp().commonssPopupTrack(
        "PopupExposure",
        {},
        type,
        messageModalCode,
        {}
      );
      this.openMessageModal(messageModalCode);
    },
    // 公共弹窗重新授权手机号 | eb会员绑定弹框重新授权手机号
    onRecheckUser(ev) {
      const { messageModalCode } = ev;
      const isTsActive = this.getIsTsActive();
      const type = isTsActive ? "TARGET_SALES" : "NORMAL";
      getApp().commonssPopupTrack(
        "PopupExposure",
        {},
        type,
        messageModalCode,
        {}
      );
      this.openMessageModal(messageModalCode);
    },
    // 注册并且入会成功
    onRegisterSuccess(ev) {
      updatePolicyStatus();
      this.$emit("registerSuccess", ev);
    },
    // TS入会弹窗点击确认
    onInvitedMemberModalConfirm(ev) {
      const { messageModalCode } = ev;
      const isTsActive = this.getIsTsActive();
      const type = isTsActive ? "TARGET_SALES" : "NORMAL";
      getApp().commonssPopupTrack(
        "PopupExposure",
        {},
        type,
        messageModalCode,
        {}
      );
      this.openMessageModal(messageModalCode);
    },
    // TS入会弹窗点击关闭
    onInvitedMemberModalClose() {
      if (!this.ageModalChecked) {
        this.$refs.ageConfirmModalRef.open(true, this.needUpdatePrivate);
      }
    },
    // TS入会弹窗取消授权手机号
    onInvitedMemberModalCancel() {
      const isTsActive = this.getIsTsActive();
      const type = isTsActive ? "TARGET_SALES" : "NORMAL";
      getApp().commonssPopupTrack("PopupExposure", {}, type, "AUTH_CANCEL", {});
      this.openMessageModal("AUTH_CANCEL");
    },
    onMessageModalFinish(ev) {
      const isTsActive = this.getIsTsActive();
      const type = isTsActive ? "TARGET_SALES" : "NORMAL";
      this.finish("message-modal", ev);
      if (ev.key == "HISTORY_OVERSEAS_MEMBER") {
        this.$store.commit("changeIsForeignMobile", false);
      }
    },
    // 历史境外手机弹窗仅在冷启动小程序时打开
    isForeignMobile(componentName, data = {}) {
      const phoneNumberReg = /^1\d{10}$/;
      if (
        this?.phoneNumber &&
        !phoneNumberReg.test(this.phoneNumber) &&
        this.foreignMobileDialog
      ) {
        // this.onJoinMemberModalConfirm({
        //   messageModalCode: "HISTORY_OVERSEAS_MEMBER",
        // });
        // 非大陆手机号按照非会员对待,重新入会
        this.$refs.joinMemberModalRef.open();
      } else {
        this.finish(componentName, data);
      }
    },

    // 业务完成事件抛出
    finish(componentName, data = {}) {
      const opt = {
        data,
        componentName,
        location: this.location,
      };
      this.$emit("finish", opt);
    },
  },
};
</script>

<style></style>
